#!/bin/bash

SCRIPT_DIR=$(cd `dirname $0` && pwd)
cd $SCRIPT_DIR

rm -rf ./_install

if [ ! -f crypt-1.18.2.tar.xz ]; then
    wget https://github.com/libtom/libtomcrypt/releases/download/v1.18.2/crypt-1.18.2.tar.xz
fi
tar Jxvf ./crypt-1.18.2.tar.xz
if [ ! -L libtomcrypt ]; then
    ln -s libtomcrypt-1.18.2 libtomcrypt
    cd onvif_simple_server/extras
    ln -s ../../libtomcrypt-1.18.2 libtomcrypt
    cd ../..
fi

if [ ! -f v3.4.0.tar.gz ]; then
    wget https://github.com/Mbed-TLS/mbedtls/archive/refs/tags/v3.4.0.tar.gz
fi
tar zxvf ./v3.4.0.tar.gz
if [ ! -L mbedtls ]; then
    ln -s mbedtls-3.4.0 mbedtls
    cd onvif_simple_server/extras
    ln -s ../../mbedtls-3.4.0 mbedtls
    cd ../..
fi
cp -f mbedtls_config.h mbedtls/include/mbedtls/

if [ ! -f v5.7.4-stable.tar.gz ]; then
    wget https://github.com/wolfSSL/wolfssl/archive/refs/tags/v5.7.4-stable.tar.gz
fi
tar zxvf ./v5.7.4-stable.tar.gz
if [ ! -L wolfssl ]; then
    ln -s wolfssl-5.7.4-stable wolfssl
    cd onvif_simple_server/extras
    ln -s ../../wolfssl-5.7.4-stable wolfssl
    cd ../..
fi

if [ ! -f zlib-1.3.1.tar.gz ]; then
    wget https://www.zlib.net/zlib-1.3.1.tar.gz
fi
tar zxvf ./zlib-1.3.1.tar.gz
if [ ! -L zlib ]; then
    ln -s zlib-1.3.1 zlib
    cd onvif_simple_server/extras
    ln -s ../../zlib-1.3.1 zlib
    cd ../..
fi

if [ ! -f json-c-0.18.tar.gz ]; then
    wget https://s3.amazonaws.com/json-c_releases/releases/json-c-0.18.tar.gz
fi
tar zxvf ./json-c-0.18.tar.gz
if [ ! -L json-c ]; then
    ln -s json-c-0.18 json-c
    mkdir -p json-c/build
    cd onvif_simple_server/extras
    ln -s ../../json-c-0.18 json-c
    cd ../..
fi

cd onvif_simple_server

git reset --hard

patch -p1 < ../path.patch
patch -p1 < ../makefile.patch
